package ee.emhi;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

public class Satelliidid extends Activity implements OnClickListener {

	WebView wVSatelite = null;
	Button bForward, bBackward, bAuto, bPause;
	int pictureNr;
	CountDownTimer timer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.satelliidid);
		initialize();

	}

	private void initialize() {
		bForward = (Button) findViewById(R.id.bForward);
		bBackward = (Button) findViewById(R.id.bBackward);
		bAuto = (Button) findViewById(R.id.bAuto);
		bPause = (Button) findViewById(R.id.bPause);
		wVSatelite = (WebView) findViewById(R.id.wView);
		wVSatelite.getSettings().setBuiltInZoomControls(true);
		wVSatelite.getSettings().setLoadWithOverviewMode(true);	

		wVSatelite.loadUrl("http://www.emhi.ee/ilma_andmed/sat/ir108_01.jpg");
		wVSatelite.setInitialScale(49);
		pictureNr = 1;

		bForward.setOnClickListener(this);
		bBackward.setOnClickListener(this);
		bAuto.setOnClickListener(this);
		bPause.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bBackward:
			picBackwards();

			break;
		case R.id.bForward:
			picForward();

			break;

		case R.id.bAuto:
			bAuto.setVisibility(View.GONE);
			bPause.setVisibility(View.VISIBLE);
			autoSurf();
			timer.start();

			break;

		case R.id.bPause:
			bPause.setVisibility(View.GONE);
			bAuto.setVisibility(View.VISIBLE);
			timer.cancel();

			break;
		}

	}

	private void picBackwards() {
		if (pictureNr == 1) {
			pictureNr = 12;
		}
		if (pictureNr < 11) {
			pictureNr -= 1;
			wVSatelite.loadUrl("http://www.emhi.ee/ilma_andmed/sat/ir108_0"
					+ pictureNr + ".jpg");

		} else {
			pictureNr -= 1;
			wVSatelite.loadUrl("http://www.emhi.ee/ilma_andmed/sat/ir108_"
					+ pictureNr + ".jpg");
			if (pictureNr == 12)
				pictureNr = 1;
		}
	}

	private void picForward() {
		if (pictureNr < 9) {

			pictureNr += 1;
			wVSatelite.loadUrl("http://www.emhi.ee/ilma_andmed/sat/ir108_0"
					+ pictureNr + ".jpg");

		} else {
			pictureNr += 1;
			wVSatelite.loadUrl("http://www.emhi.ee/ilma_andmed/sat/ir108_"
					+ pictureNr + ".jpg");
			if (pictureNr == 12)
				pictureNr = 1;
		}
	}

	private void autoSurf() {
		timer = new CountDownTimer(500, 1000) {

			@Override
			public void onTick(long millisUntilFinished) {
				Log.v("Hei", "seconds remaining: " + millisUntilFinished / 1000);
			}

			@Override
			public void onFinish() {
				picForward();
				timer.start();
			}

		};
	}
}
